local skel = fk.CreateSkill{
  name = "div_heg__yinpan"
}
local H = require "packages/hegemony/util"
local U = require "packages/utility/utility"
---@type ActiveSkillSpec
local yinpan = {
  name = "div_heg__yinpan",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and Self.id ~= to_select
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local target = effect.tos[1]
    room:setPlayerMark(target, "yinpan_safe-phase", 1)
    for _, p in ipairs(room.alive_players) do
      if not H.compareKingdomWith(p, target) and p ~= target then
        local use = U.askForUseRealCard(room, p, nil, "slash", self.name, "#yinpan-usecard:"..target.id, {
          must_targets = {target.id},
          bypass_distances = true,
        }, true, true)
        if use then
          if not use.extra_data then use.extra_data = {} end
          use.extra_data.yinpan_slash = true
          room:useCard(use)
        end
      end
    end
    if not target.dead and target:isWounded() and target:getMark("yinpan_safe-phase") > 0 then
      room:recover({
        who = target,
        num = 1,
        skillName = self.name
      })
    end
  end,
}
---@type TrigSkelSpec<DamageTrigFunc>
local yinpan_trigger = {
  refresh_events = {fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    if data.card then
      return player == target
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local e = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if e then
      local use = e.data[1]
      local dat = (use.extra_data or {}).yinpan_slash
      if dat then
        if target:getMark("yinpan_safe-phase") > 0 then
          player.room:setPlayerMark(target, "yinpan_safe-phase", 0)
        end
        player.room:addPlayerMark(target, "@yinpan_mod", data.damage)
      end
    end
  end,
}
---@type TrigSkelSpec<TrigFunc>
local yinpan_delay = {
  refresh_events = {fk.TurnEnd, fk.Death},
  can_refresh = function(self, event, target, player, data)
    return player:getMark("@yinpan_mod") > 0 and player == target
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@yinpan_mod", 0)
  end,
}
---@type TargetModSpec
local yinpan_mod = {
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@yinpan_mod") > 0 and scope == Player.HistoryPhase then
      return player:getMark("@yinpan_mod")
    end
  end,
}
skel:addEffect("active", yinpan)
skel:addEffect(fk.Damaged, yinpan_trigger)
skel:addEffect(fk.TurnEnd, yinpan_delay)
skel:addEffect(fk.Death, yinpan_delay)
skel:addEffect("targetmod", yinpan_mod)
return skel